﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using CSP.Model;
using CSP.Model.CSP;
using CSP.Common.Factories;
using System.Web.UI;
using CSP.Model.CSPBBS;
using CSP.Bll;
using CSP.Model.CSPEnum;
using System.Configuration;
using CSP.Common.Tools;
using CSP.Common.Providers;
using CSP.Common.IProviders;

namespace CSP.Common.Web.Providers
{

    public class UserProvider
    {
        private string _userName;

        private int _uid;

        private Page _page;

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get { return _userName; }

            set { _userName = value; }
        }

        /// <summary>
        /// 用户Id
        /// </summary>
        public int Uid
        {
            get
            {
                return _uid;
            }
            set
            {
                _uid = value;
            }
        }


        /// <summary>
        /// 用户状态，1本站用户，2 第三方用户
        /// </summary>
        public string UserStatus
        { get; set; }


        public UserProvider(Page page)
        {
            _page = page;
            InitUser(_page);
        }

        /// <summary>
        /// 获取当前用户的基本信息
        /// </summary>
        /// <param name="isLoadMemberProfile">是否记载用户资料,默认false 不加载</param>
        /// <returns></returns>
        public Member GetUserInfo(bool isLoadMemberProfile = false)
        {
            return GetUserInfoByBll(isLoadMemberProfile);
        }

        /// <summary>
        /// 退出
        /// </summary>
        public void LoginOut()
        {
            CookieFactory.GetInstace().RemoveCookie(_page, "auth");
            CookieFactory.GetInstace().RemoveCookie(_page, "saltkey");
            HttpContext.Current.Session.Remove("UserName");
            HttpContext.Current.Session.Remove("OtherUserInfo");
        }

        private void InitUser(Page page)
        {
            _userName = GetUserNameBySession();
            _uid = GetUidBySession();
            if (_userName == "")
            {
                Member userMember = GetUserNameByCookie(page);

                if (userMember != null)
                {
                    _userName = userMember.UserName;
                    _uid = userMember.Id;

                    SetUserNameForSession(_uid, _userName);
                }

            }
        }

        /// <summary>
        /// 从Session 值中获取UserName
        /// </summary>
        /// <returns></returns>
        private string GetUserNameBySession()
        {
            object userName = HttpContext.Current.Session["UserName"];
            if (userName == null)
            {
                return "";
            }

            return userName.ToString();
        }

        /// <summary>
        /// 从Session 值中获取Uid
        /// </summary>
        /// <returns></returns>
        private int GetUidBySession()
        {
            object uid = HttpContext.Current.Session["Uid"];
            if (uid == null)
            {
                return 0;
            }

            return Convert.ToInt32(uid);
        }

        /// <summary>
        /// 对用户Id 和userName 设置Session 缓存
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="userName"></param>
        private void SetUserNameForSession(int uid, string userName)
        {
            if (!string.IsNullOrEmpty(userName))
            {
                HttpContext.Current.Session["UserName"] = userName;
                HttpContext.Current.Session["Uid"] = uid;
            }
        }

        private Member GetUserNameByCookie(Page page)
        {
            string authKey = AuthCode.MD5(ConfigurationManager.AppSettings["AuthKey"].ToString() + CookieFactory.GetInstace().GetCookie(page, "saltkey"));
            string cookieAuth = CookieFactory.GetInstace().GetCookie(page, "auth");
            try
            {
                
                if (!string.IsNullOrEmpty(cookieAuth))
                {
                    string authCode = CommonTool.DiscuzAuthcodeDecode(cookieAuth, authKey).Replace("\t", "|");
                    var user = UserAuth(Convert.ToInt32(authCode.Split('|')[1]), authCode.Split('|')[0]);
                    if (user != null)
                    {
                        return user;
                    }
                }
            }
            catch (Exception ex)
            {
                ILoggerProvider loggerProvider = LoggerFactory.GetErrorLogger();
                loggerProvider.Error("cookie用户验证错误 authkey:" + authKey + " cookieAuth" + cookieAuth, ex);
            }
            return null;
        }

        /// <summary>
        /// 从Bll中获取当前用户的基本信息
        /// </summary>
        /// <returns></returns>
        private Member GetUserInfoByBll(bool isLoadMemberProfile = false)
        {
            Member result = null;
            using (var userInfoBll = CSPBllFactory.GetInstance().GetUserInfoBll())
            {
                result = userInfoBll.GetUser(_userName, isLoadMemberProfile);
            }
            return result;
        }

        /// <summary>
        /// 用户验证
        /// </summary>
        /// <returns></returns>
        private Member UserAuth(int uid, string pwd)
        {
            Member result = null;
            using (var userInfoBll = CSPBllFactory.GetInstance().GetUserInfoBll())
            {
                result = userInfoBll.GetUser(uid, pwd);
            }
            return result;
        }


    }
}
